<template>
  <div class="zh-classTime-setting">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-right fr">
          <el-button type="primary" @click="getData">刷新</el-button>
          <el-button type="primary" @click="saveBox()">添加课时</el-button>
          <el-button type="danger" @click="deleteLast">批量删除</el-button>
        </div>
      </div>

      <div
        class="zh-table-contents"
        v-loading="loading.status"
        :element-loading-text="loading.txt"
      >
        <el-table
          :data="listData"
          @selection-change="changeHander"
          border
          max-height="600"
          style="width: 100%"
        >
          <el-table-column type="selection" width="50" align="center" fixed>
          </el-table-column>
          <el-table-column
            label="节次"
            type="index"
            align="center"
            width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.section_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="start_time"
            label="开始时间（时:分）"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="end_time"
            label="结束时间（时:分）"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="5"
            label="操作"
            align="center"
            width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button @click="saveBox(scope.$index)" type="text"
                >编辑</el-button
              >
              <el-button
                @click="delRow(scope.row)"
                type="text"
                class="delete-button"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加课时 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="saveBoxStatus"
      class="classHour"
      width="400px"
    >
      <el-form
        :model="addForm"
        ref="addForm"
        :rules="rules"
        status-icon
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="节次：" style="text-align: left">
          <el-input
            maxlength="5"
            show-word-limit
            v-model="addForm.section_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="开始时间：" prop="start_time">
          <el-time-select
            placeholder="请选择开始时间"
            v-model="addForm.start_time"
            :editable="false"
            @change="changeStartTime"
            :picker-options="{
              start: '00:00',
              step: '00:05',
              end: '24:00',
              minTime: timeLimit.startTimeMinTime,
              maxTime: timeLimit.startTimeMaxTime
            }"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="结束时间：" prop="end_time">
          <el-time-select
            placeholder="请选择结束时间"
            v-model="addForm.end_time"
            :editable="false"
            :picker-options="{
              start: '00:00',
              step: '00:05',
              end: '24:00',
              minTime: timeLimit.endTimeMinTime,
              maxTime: timeLimit.endTimeMaxTime
            }"
          >
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveBoxStatus = false">取消</el-button>
        <el-button type="primary" @click="saveClassRoom">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loading: {
        status: false,
        txt: "获取数据..."
      },
      listData: [],
      saveBoxStatus: false,
      addForm: {
        id: 0,
        start_time: "",
        end_time: "",
        section_name: ""
      },
      rangTime: [],
      rules: {
        start_time: [
          { validator: this.validateTime1, trigger: "blur", required: true }
        ],
        end_time: [
          { validator: this.validateTime2, trigger: "blur", required: true }
        ]
      },
      timeLimit: {
        startTimeMinTime: "00:00",
        startTimeMaxTime: "24:00",
        endTimeMinTime: "00:00",
        endTimeMaxTime: "24:00"
      },
      tempInx: -1,
      title: "",
      changeHans: [],
      sectionInx: 0
    };
  },
  created() {
    this.getData();
  },
  watch: {
    saveBoxStatus() {
      if (this.saveBoxStatus === false) {
        this.$refs.addForm.clearValidate();
        this.addForm = {
          id: 0,
          start_time: "",
          end_time: "",
          section_name: ""
        };
      }
    }
  },
  methods: {
    saveData() {
      let success = data => {
        this.$message.success(data.msg);
        this.getData();
      };

      console.info(this.listData);
      this.$ajax.post("api/school/timeset", this.listData, {
        func: { success: success }
      });
    },
    /**
     * 验证开始时间
     */
    validateTime1(rule, value, callback) {
      if (value === "" || value === null) {
        return callback(new Error("请选择时间"));
      } else {
        if (
          this.addForm.end_time &&
          this.addForm.start_time >= this.addForm.end_time
        ) {
          this.addForm.start_time = "";
          return callback(new Error("开始时间不可以大于等于结束时间"));
        } else {
          callback();
        }
      }
    },
    /**
     * 验证结束时间
     */
    validateTime2(rule, value, callback) {
      if (value === "" || value === null) {
        return callback(new Error("请选择时间"));
      } else {
        callback();
      }
    },
    changeHander(vals) {
      this.changeHans = vals;
    },
    delRow(row) {
      let cancel = data => {};
      let yes = data => {
        const params = {
          id: row.id
        };
        const success = data => {
          this.$message.success(data.msg);
          this.getData();
        };
        this.$ajax.delete("api/school/timeset", {
          params,
          func: { success: success }
        });
      };
      this.e_confirm({ yes: yes, cancel: cancel, txt: "确定要删除该课时吗？" });
    },
    deleteLast() {
      if (this.changeHans.length === 0) {
        this.$message.warning("请选择要删除的选项");
        return false;
      }

      let cancel = data => {};
      let yes = data => {
        const ids = this.changeHans.map(item => item.id);
        const params = {
          id: ids
        };
        const success = data => {
          this.$message.success(data.msg);
          this.getData();
        };
        this.$ajax.delete("api/school/timeset", {
          params,
          func: { success: success }
        });
      };
      this.e_confirm({ yes: yes, cancel: cancel, txt: "确定要删除课时吗？" });
    },

    changeStartTime(start_time) {
      this.timeLimit.endTimeMinTime = start_time;
      this.timeLimit.endTimeMaxTime =
        this.tempInx > -1 && this.tempInx < this.listData.length - 1
          ? this.listData[this.tempInx + 1].start_time
          : "24:00";
    },
    saveBox(inx = -1) {
      this.tempInx = inx;
      this.saveBoxStatus = true;
      if (inx > -1) {
        this.title = "编辑课时";
        this.addForm = deep_clone(this.listData[this.tempInx]);
        this.timeLimit.startTimeMinTime =
          this.tempInx > 0 ? this.listData[this.tempInx - 1].end_time : "00:00";
        this.timeLimit.startTimeMaxTime =
          this.tempInx < this.listData.length - 1
            ? this.listData[this.tempInx + 1].start_time
            : "24:00";
        this.timeLimit.endTimeMinTime = this.listData[this.tempInx].start_time;
        this.timeLimit.endTimeMaxTime =
          this.tempInx < this.listData.length - 1
            ? this.listData[this.tempInx + 1].start_time
            : "24:00";
      } else {
        this.title = "添加课时";
        this.addForm.section_name =
          this.listData.length > 0
            ? `第${this.numberToChinese(this.listData.length + 1)}节`
            : `第${this.numberToChinese(1)}节`;
        this.timeLimit.startTimeMinTime =
          this.listData.length > 0
            ? this.listData[this.listData.length - 1].end_time
            : "00:00";
        this.timeLimit.startTimeMaxTime = "24:00";
        this.timeLimit.endTimeMinTime = this.timeLimit.startTimeMinTime;
        this.timeLimit.endTimeMaxTime = "24:00";
      }
    },

    numberToChinese(num) {
      const chineseNums = [
        "",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九"
      ];
      const units = ["", "十", "百", "千", "万", "亿"]; // 万亿以内的单位

      // 将数字转换为字符串，并反转
      const numStr = num
        .toString()
        .split("")
        .reverse();
      let chineseStr = "";

      for (let i = 0; i < numStr.length; i++) {
        const digit = parseInt(numStr[i]);
        if (digit !== 0 || chineseStr !== "") {
          chineseStr = chineseNums[digit] + units[i] + chineseStr;
        }
      }

      // 去除末尾的零
      chineseStr = chineseStr
        .replace(/零[十百千]/g, "零")
        .replace(/零+/g, "零")
        .replace(/^零+/, "");

      return chineseStr;
    },
    saveClassRoom() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.tempInx > -1) {
            this.listData[this.tempInx] = this.addForm;
            this.handleEdit();
          } else {
            this.listData.push(this.addForm);
            this.handleAdd();
          }
          this.saveBoxStatus = false;
        } else {
          return false;
        }
      });
    },

    handleEdit() {
      const success = data => {
        this.$message.success(data.msg);
        this.getData();
      };
      this.$ajax.put("api/school/timeset", this.addForm, {
        func: { success: success }
      });
    },

    handleAdd() {
      const success = data => {
        this.$message.success(data.msg);
        this.getData();
      };
      this.$ajax.post("api/school/timeset", this.addForm, {
        func: { success: success }
      });
    },
    getData() {
      this.loading.status = true;
      // 重写成功回调
      let success = data => {
        this.loading.status = false;
        this.listData = data.data;
        this.$forceUpdate(); //强制渲染
      };
      let fail = data => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };
      this.$ajax.get("api/school/timeset", {
        params: {},
        func: { success: success, fail: fail }
      });
    }
  }
};
</script>
<style lang="scss">
.zh-classTime-setting {
  .el-table__body-wrapper table tbody {
    td:nth-child(4) {
      padding: 0;
    }
  }
  .classHour {
    .el-form-item__content {
      .el-date-editor {
        width: 100%;
      }
    }
  }
}
</style>
